<template>
  <div>
    <div class="mb-3">
      <el-button
        v-if="customerData.project_status === '0' || customerData.project_status === '2'"
        type="primary"
        @click="addKeyvendor"
      >
        增加合作商
      </el-button>
      <el-button
        v-if="customerData.project_status === '0' || customerData.project_status === '2'"
        type="primary"
        @click="dialogImportVisible = true"
      >
        <i class="fa fa-fw fa-upload"></i>
        导入合作商信息
      </el-button>
    </div>
    <loading-wrap>
      <el-table border :data="tableData">
        <el-table-column align="center" label="类型">
          <template slot-scope="scope">
            {{ enumSmType[scope.row.sm_type] }}
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="left" label="合作商名称" prop="sm_name">
          <template slot-scope="scope">
            <span>{{ scope.row.sm_name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="联系电话" prop="sm_phone">
          <template slot-scope="scope">
            <span>{{ scope.row.sm_phone || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="合作时间" prop="sm_year">
          <template slot-scope="scope">
            <span>{{ scope.row.sm_year || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商品及型号" prop="sm_product">
          <template slot-scope="scope">
            <span>{{ scope.row.sm_product || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单位" prop="unit">
          <template slot-scope="scope">
            <span>{{ scope.row.unit || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单价" prop="sm_price">
          <template slot-scope="scope">
            <span>{{ scope.row.sm_price || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" prop="sm_amount">
          <template slot-scope="scope">
            <span>{{ scope.row.sm_amount || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="总额(万元)" prop="sm_total">
          <template slot-scope="scope">
            <span>{{ scope.row.sm_total || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="合作年限" prop="coo_years">
          <template slot-scope="scope">
            <span>{{ scope.row.coo_years || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实力">
          <template slot-scope="scope">
            <span v-if="scope.row.sm_type === '1'">
              <el-tooltip
                class="item"
                effect="dark"
                placement="top-start"
                :content="enumSupplierStrengthType[scope.row.supplier_strength_type]"
              >
                <span v-if="scope.row.supplier_strength_type">
                  {{
                    enumSupplierStrengthType[scope.row.supplier_strength_type].substring(0, 3) +
                    '...'
                  }}
                </span>
                <span v-else>-</span>
              </el-tooltip>
            </span>
            <span v-else>
              <el-tooltip
                class="item"
                effect="dark"
                placement="top-start"
                :content="enumSellerStrengthType[scope.row.strength_type]"
              >
                <span v-if="scope.row.strength_type">
                  {{ enumSellerStrengthType[scope.row.strength_type].substring(0, 3) + '...' }}
                </span>
                <span v-else>-</span>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="价格变动情况">
          <template slot-scope="scope">
            <span v-if="scope.row.sm_type === '1'">
              {{ enumPriceWaveType[scope.row.material_wave_type] || '-' }}
            </span>
            <span v-else>{{ enumPriceWaveType[scope.row.price_wave_type] || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark">
          <template slot-scope="scope">
            <span>{{ scope.row.remark || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="customerData.project_status === '0' || customerData.project_status === '2'"
          align="center"
          fixed="right"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button class="py-0 px-1" type="text" @click="edit(scope.row)">
              <i class="fa fa-edit"></i>
            </el-button>
            <el-button class="py-0 px-1 text-danger" type="text" @click="deleteData(scope.row)">
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 30px">
        <el-row :gutter="20">
          <el-col :span="6">
            <div>
              供货商总额：
              <span v-show="Gall" style="color: #00b3ee">{{ Gall + '万元' }}</span>
            </div>
          </el-col>
          <el-col :offset="1" :span="6">
            <div>
              销售商总额：
              <span v-show="Xall" style="color: #00b3ee">{{ Xall + '万元' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </loading-wrap>

    <form-component
      ref="fc"
      :auto-init="false"
      :form-data="formData"
      :table-data="editData"
      :table-id="tableId"
      :table-name="tableName"
      :visible.sync="editVisible"
      @success="getData"
    ></form-component>

    <el-dialog
      title="新增合作信息"
      width="80%"
      :close-on-click-modal="false"
      :before-close="handleClose"
      :visible.sync="dialogVisible"
    >
      <el-table border v-loading="industloading" :data="postData">
        <el-table-column align="center" label="类型" width="120px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.sm_type">
              <el-option
                v-for="(value, key) in enumSmType"
                :key="key"
                :label="value"
                :value="key"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="合作商名称" width="90px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sm_name"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="联系电话" width="90px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sm_phone"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="合作时间" width="120px">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.sm_year"
              placeholder="时间"
              style="width: 100%"
              type="year"
              value-format="yyyy"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column align="center" label="合作年限" width="90px">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.coo_years"
              style="width: 100%"
              :controls="false"
              :min="0"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商品及型号" width="90px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sm_product"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单位" width="90px">
          <template slot-scope="scope">
            <select-unit v-model="scope.row.unit" type="unit"></select-unit>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单价" width="90px">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.sm_price"
              style="width: 100%"
              :controls="false"
              @change="handleInput(scope.row)"
              :min="0"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" width="90px">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.sm_amount"
              style="width: 100%"
              :controls="false"
              @change="handleInput(scope.row)"
              :min="0"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="总额(万元)" width="90px">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.sm_total"
              style="width: 100%"
              :controls="false"
              :min="0"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实力" width="90px">
          <template slot-scope="scope">
            <el-select v-if="scope.row.sm_type === '1'" v-model="scope.row.supplier_strength_type">
              <el-option
                v-for="(value, key) in enumSupplierStrengthType"
                :key="key"
                :label="value"
                :value="key"
              ></el-option>
            </el-select>
            <el-select v-else v-model="scope.row.strength_type">
              <el-option
                v-for="(value, key) in enumSellerStrengthType"
                :key="key"
                :label="value"
                :value="key"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="价格变动情况" width="90px">
          <template slot-scope="scope">
            <el-select v-if="scope.row.sm_type === '1'" v-model="scope.row.material_wave_type">
              <el-option
                v-for="(value, key) in enumPriceWaveType"
                :key="key"
                :label="value"
                :value="key"
              ></el-option>
            </el-select>
            <el-select v-else v-model="scope.row.price_wave_type">
              <el-option
                v-for="(value, key) in enumPriceWaveType"
                :key="key"
                :label="value"
                :value="key"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" width="90px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="60px">
          <template slot-scope="scope">
            <el-button class="py-0 px-1 text-danger" type="text" @click="deleteArray(scope.$index)">
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-loading="industloading" class="mt-3">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-button @click="postData.push({})">新增一行</el-button>
          </el-col>
          <el-col :span="2">
            <el-button style="width: 100%" @click="clearClose">取消</el-button>
          </el-col>
          <el-col :span="2">
            <el-button style="width: 100%" @click="submit"><span>保存</span></el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <import-excel
      :visible.sync="dialogImportVisible"
      title="导入供销商信息"
      :post-api="postUrl"
      excel-template="/static/files/供销货商导入模板.xlsx"
      @success="handleImportSucess"
    ></import-excel>
  </div>
</template>

<script>
import { DatePicker } from 'element-ui'
import SelectUnit from '@/credit/components/select/SelectUnit'
import FormComponent from '@/components/FormComponent'
import {
  enumPriceWaveType,
  enumSellerStrengthType,
  enumSmType,
  enumSupplierStrengthType,
} from '@/credit/plugins/enum'
import ImportExcel from '@/components/ImportExcel'
export default {
  components: {
    SelectUnit,
    FormComponent,
    ImportExcel,
  },
  props: {},
  data() {
    return {
      dialogImportVisible: false,
      postUrl: '',
      enumSmType,
      enumSupplierStrengthType,
      enumSellerStrengthType,
      enumPriceWaveType,
      tableName: 'datum_customer_business_sm',
      editVisible: false,
      tableData: [],
      tableId: '',
      editData: {},
      formData: {
        sm_type: {
          type: 'radio',
          label: '类型',
          value: '1',
          inline: true,
          enumType: enumSmType,
          required: true,
          onClick: v => {
            const type = +v === 1
            const ref = this.$refs.fc
            ref.setKey('supplier_strength_type', 'hide', !type, '1')
            ref.setKey('strength_type', 'hide', type, '1')
            ref.setKey('material_wave_type', 'hide', !type, '1')
            ref.setKey('price_wave_type', 'hide', type, '1')
          },
        },
        coo_years: { type: 'text', label: '合作年限', value: '', required: true },
        sm_name: { type: 'text', label: '合作商名称', value: '', required: true },
        sm_year: {
          type: 'component',
          label: '合作时间',
          value: '',
          required: true,
          component: DatePicker,
          attrs: {
            style: 'width: 360px',
            type: 'year',
            valueFormat: 'yyyy',
          },
        },
        sm_phone: { type: 'text', label: '联系电话', value: '' },
        sm_product: { type: 'text', label: '商品及型号', value: '' },
        unit: { type: 'text', label: '单位', value: '' },
        sm_price: {
          type: 'number',
          label: `单价`,
          value: '',
          unit: '元',
          step: 0.01,
          onInput: (key, val, form) => {
            const ref = this.$refs.fc
            ref.setKey('sm_total', 'value', this.getTotal(val, form.sm_amount.value))
          },
        },
        sm_amount: {
          type: 'number',
          label: `数量`,
          value: '',
          step: 0.01,
          onInput: (key, val, form) => {
            const ref = this.$refs.fc
            ref.setKey('sm_total', 'value', this.getTotal(val, form.sm_price.value))
          },
        },
        sm_total: { type: 'number', label: `总额`, value: '', unit: '万元', step: 0.0001 },
        supplier_strength_type: {
          type: 'radio',
          label: '实力',
          value: '1',
          inline: true,
          enumType: enumSupplierStrengthType,
        },
        strength_type: {
          type: 'radio',
          label: '实力',
          value: '1',
          inline: true,
          enumType: enumSellerStrengthType,
          hide: true,
        },
        material_wave_type: {
          type: 'radio',
          label: '原材料价格波动',
          value: '1',
          inline: true,
          enumType: enumPriceWaveType,
        },
        price_wave_type: {
          type: 'radio',
          label: '价格波动',
          value: '1',
          inline: true,
          enumType: enumPriceWaveType,
          hide: true,
        },
        remark: { type: 'text', label: '备注', value: '' },
      },
      Gall: 0,
      Xall: 0,
      dialogVisible: false,
      postData: [{}, {}, {}],
      industloading: false,
    }
  },
  computed: {},
  watch: {},
  created() {
    this.customerData = JSON.parse(sessionStorage.getItem('customer_related_view'))
    this.id = this.$route.query.id || sessionStorage.getItem('customer_related_id')
    this.postUrl =
      '/api/credit/import/?importKey=datum_customer_business_sm_template&where=' +
      encodeURIComponent(
        '"datum_customer_business_sm.service_id".eq(' + this.$store.getters.org.clientId + ')'
      ) +
      encodeURIComponent('&"datum_customer_business_sm.customer_related_id".eq(' + this.id + ')')

    this.getData()
  },
  mounted() {},
  methods: {
    addKeyvendor() {
      this.dialogVisible = true
    },
    deleteArray(index) {
      this.postData.splice(index, 1)
    },
    submit() {
      let customerData = {}
      let data = []
      for (let p of this.postData) {
        if (JSON.stringify(p) !== '{}') {
          const localCustomerData = sessionStorage.getItem('customer_related_view')
          try {
            customerData = JSON.parse(localCustomerData)
          } catch (e) {
            console.error(new Error(e))
          }
          p.customer_id = customerData.customer_id
          p.customer_name = customerData.customer_name
          p.customer_related_id = this.id
          data.push(p)
        }
      }
      if (data.length > 0) {
        this.toSave(data)
      } else {
        this.$message.warning('请输入信息！')
      }
    },
    async toSave(data) {
      this.industloading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addBatch('credit', this.tableName, data)
      )
      this.industloading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.getData()
        this.clearClose()
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    clearClose() {
      this.postData = [{}, {}, {}]
      this.dialogVisible = false
    },
    handleClose() {
      this.dialogVisible = false
    },
    getData() {
      this.Xall = 0
      this.Gall = 0
      this.$api
        .getData(
          'credit',
          this.tableName,
          {
            'customer_related_id.eq': this.id,
          },
          { sm_type: 'asc' }
        )
        .then(res => {
          this.tableData = res.data
          if (!this.tableData) {
            return
          }
          for (let p of this.tableData) {
            if (p.sm_type === '1') {
              this.Gall += Number(p.sm_total)
            } else {
              this.Xall += Number(p.sm_total)
            }
          }
          this.Xall = this.Xall.toFixed(4)
          this.Gall = this.Gall.toFixed(4)
        })
    },

    handleInput(row) {
      row.sm_total = this.getTotal(row.sm_price, row.sm_amount)
    },

    getTotal(price, amount) {
      return Math.round(Math.round(this.getNum(price) * this.getNum(amount) * 100) / 100) / 10000
    },

    getNum(num) {
      let n = Number.parseFloat(num)
      return isNaN(n) ? 0 : n
    },
    // 导入
    handleImportSucess() {
      this.getData()
      this.dialogImportVisible = false
    },
    edit(p) {
      this.editVisible = true
      this.tableId = p ? p.id : ''
      this.editData = p
    },
    deleteData(item) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            const [res] = await this.$utils.promise(
              this.$api.deleteData('credit', this.tableName, item.id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getData()
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
  },
}
</script>

<style scoped>
.table td {
  vertical-align: middle;
}
</style>
